<?php

class Core_Backend_Component_Promotion_Controller_Concessions extends Dcmp_Component_Controller {

    public function indexAction($pageindex = 1, $pagesize = 20, $sort = 'id', $dir = 'asc') {
        $this->getHistory()->record();
        $validator = $this->getRequest()->getValidator('filter');
        $collection = App::getModel('promotion/collection_concessions')
                        ->pagination($pageindex, $pagesize)
                        ->sortBy($sort, $dir);
        if ($validator->isNotEmpty('name')) {
            $collection->filterByName($validator->getValue('name'));
        }
        if ($validator->isNotEmpty('status')) {
            $collection->filterByStatus($validator->getValue('status'));
        }
        if ($validator->isNotEmpty('tag')) {
            $collection->filterByTag($validator->getValue('tag'));
        }
        if ($validator->isNotEmpty('categoryname')) {
            $collection->filterByCategoryName($validator->getValue('categoryname'));
        }
        $collection->load();
        $records = $collection->loadCount();
        return $this->viewResult(array('list' => $collection, 'records' => $records));
    }

    public function createAction() {
        $categories = App::getModel('promotion/collection_concessions_category')->load();
        $themes = App::getModel('design/collection_page_theme')
                        ->filterByType('concessions')
                        ->filterByEnabled(1)
                        ->load();
        return $this->viewResult(array('categories' => $categories, 'themes'=>$themes));
    }

    public function editAction($id) {
        $model = App::getModel('promotion/concessions')->load($id);
        return $this->createAction()->setModel($model);
    }

    public function savePostAction($status = 'draft') {
        $data = $this->getRequest()->getForm('concessions');
        $model = App::getModel('promotion/concessions');
        if (isset($data['id']) && !empty($data['id'])) {
            $model->load($data['id']);
        }
        $model->addData($data)->setStatus($status);
        if (($errors = $model->validate() === TRUE)) {
            $model->save();
            $this->getMessager()->addInform($this->__('share.message.success'));
            return $this->redirectResult($this->getHistoryUrl('promotion/concessions/index'));
        } else {
            $this->getMessager()->addError($this->__('share.message.fail'))
                    ->addError($errors);
            return $this->createAction()->setModel($model);
        }
    }
    
    public function reviewPostAction($ids, $status, $statusmessage = ''){
    	if($status == 'published'){
    		App::getModel('promotion/concessions')->publish($ids);
    	}elseif($status = 'forbidden'){
    		App::getModel('promotion/concessions')->forbid($ids, $statusmessage);
    	}
    	return $this->redirectResult($this->getHistoryUrl('promotion/concessions/index'));
    }

    public function generateTagAction() {
        $articles = App::getModel('promotion/collection_concessions')->load();
        $tagModel = App::getModel('tag/keyword');
        $transaction = Kd_Db_Factory::getTransaction();
        try {
            $transaction->begin();
            foreach ($articles as $article) {
                $tags = explode(' ', $article->getTag());
                $tagModel->removeTagRecord($article->getId(), 'concessions', $transaction)
                        ->addTagRecord($tags, $article->getId(), 'concessions', $transaction);
            }
            $transaction->commit();
        } catch (Exception $ex) {
            $transaction->rollback();
            throw $ex;
        }
        $this->getMessager()->addInform($this->__f('share.message.success'));
        return $this->redirectResult($this->getHistoryUrl('subject/content/index'));
    }

    public function categoryIndexAction($pageindex = 1, $pagesize = 20, $sort = 'id', $dir = 'asc') {
        $this->getHistory()->record();
        $list = App::getModel('promotion/collection_concessions_category')
                        ->pagination($pageindex, $pagesize)
                        ->load();
        $records = $list->loadCount();
        return $this->viewResult(array('list' => $list, 'records' => $records));
    }

    public function categoryCreateAction() {
        $themes = App::getModel('design/collection_page_theme')
                        ->filterByType('concessions')
                        ->filterByEnabled(1)
                        ->load();
        return $this->viewResult(array('themes' => $themes));
    }

    public function categoryEditAction($id) {
        $model = App::getModel('promotion/concessions_category')->load($id);
        return $this->categoryCreateAction()->setModel($model);
    }

    public function categoryApplyAction() {
        return $this->saveCategoryModel();
    }

    public function categorySaveAction() {
        return $this->saveCategoryModel(TRUE);
    }

    private function saveCategoryModel($return = FALSE) {
        $data = $this->getRequest()->getForm('category');
        $model = App::getModel('promotion/concessions_category');
        if (isset($data['id']) && !empty($data['id'])) {
            $model->load($data['id']);
        }
        $model->addData($data);
        if (($errors = $model->validate() === TRUE)) {
            $model->save();
            $this->getMessager()->addInform($this->__f('share.message.saveSuccess', '{promotion.label.concessions_category}', $model->getName()));
            return $return ?
                    $this->redirectResult($this->getHistoryUrl('promotion/concessions/category-index')) :
                    $this->redirectResult($this->getUrl(array('id' => $model->getIdValue()), 'edit'));
        } else {
            $this->getMessager()->addError($this->__f('share.message.saveFail', '{promotion.label.concessions_category}', $model->getName()))
                    ->addError($errors);
            return $this->createAction()->setModel($model);
        }
    }

    public function importAction() {
        return $this->viewResult();
    }

    public function importPostAction() {
        $file = $this->getRequest()->getFile('file');
        $filename = $file->saveTo(DP_TMP . 'import' . DS . 'concessions');
        $datas = fopen($filename, "r");
//        $names = fgetcsv($datas);
        $nameIndexes = array('name' => 0,
            'category_id' => 1,
            'tag' => 2,
            'start_time' => 3,
            'end_time' => 4,
            'condition' => 5,
            'mode' => 6,
            'detail' => 7,
            'picture' => 8,
            'poi_ids' => 9,
            'status' => 10);
        fgetcsv($datas);
        while ($data = fgetcsv($datas)) {
            $model = App::getModel('promotion/concessions')
                            ->setName($data[$nameIndexes['name']])
                            ->setTag($data[$nameIndexes['tag']])
                            ->setStartTime($data[$nameIndexes['start_time']])
                            ->setEndTime($data[$nameIndexes['end_time']])
                            ->setCondition($data[$nameIndexes['condition']])
                            ->setMode($data[$nameIndexes['mode']])
                            ->setDetail($data[$nameIndexes['detail']])
                            ->setStatus($data[$nameIndexes['status']]);
            if (isset($data[$nameIndexes['poi_ids']]) && !empty($data[$nameIndexes['poi_ids']])) {
                $model->setCategoryId(1);
                $model->setPoiIds(explode(',', $data[$nameIndexes['poi_ids']]));
            } else {
                $model->setCategoryId(2);
            }
            if (!isset($data[$nameIndexes['start_time']]) || empty($data[$nameIndexes['start_time']])) {
                $model->setStartTime(date('Y-m-d', strtotime('2010-12-1')));
            }
            if (!isset($data[$nameIndexes['end_time']]) || empty($data[$nameIndexes['end_time']])) {
                $model->setEndTime(date('Y-m-d', strtotime('2011-1-1')));
            }
            if (!isset($data[$nameIndexes['status']]) || empty($data[$nameIndexes['status']])) {
                $model->setStatus('published');
            }
            if (isset($data[$nameIndexes['picture']]) && !empty($data[$nameIndexes['picture']])) {
                $arr = explode(',', $data[$nameIndexes['picture']]);
                $pictures = array();
                foreach ($arr as $picture) {
                    $pictures[] = '/pub/media/promotion/concessions/20101228/' . $picture;
                }
                $model->setPicture(implode(',', $pictures));
            }
            $model->save();
        }

        $this->getMessager()->addInform($this->__f('share.message.success'));
    }

}